package cz.najman.emdroid.listener;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;
import cz.najman.emdroid.R;

public class ShowDialogOnDataUpdatedListener extends DefaultOnDataUpdatedListener {
	
	//private static final String TAG = "AbstractShowDialogOnDataUpdatedListener";

	private final Context mContext;	
	private Dialog mDialog;
	private String mErrorMessage;
	private String mSuccesMessage;
	private String mRunningMesssage;
	private String mDialogWindowText;
	private int mRunningUpdates = 0;

	public ShowDialogOnDataUpdatedListener(Context context) {
		mContext = context;
	}

	protected void onRunning(Class objectId) {
		
		if(mRunningUpdates == 0){
			if (mDialogWindowText == null)
				mDialogWindowText = mContext.getResources().getString(R.string.retrieving_data_default_dialog_window_text);

			mDialog = ProgressDialog.show(mContext, mDialogWindowText,mRunningMesssage);
		}	

		mRunningUpdates++;
		
		super.onRunning(objectId);
	}

	protected void onFinished(Class objectId) {
		
		if ((--mRunningUpdates == 0)) {
			if (mDialog != null) {
				mDialog.dismiss();
				mDialog = null;
			}

			if (mSuccesMessage != null) {
				Toast.makeText(mContext, mSuccesMessage, Toast.LENGTH_SHORT).show();
			}
		}
		
		super.onFinished(objectId);
	}

	protected void onError(Class objectId) {		
		
		if ((--mRunningUpdates == 0)) {
			if (mDialog != null){
				mDialog.dismiss();
				mDialog = null;
			}
		}
		
		if (mErrorMessage == null)
			mErrorMessage = mContext.getResources().getString(R.string.retrieving_data_default_error_message);

		Toast.makeText(mContext, mErrorMessage, Toast.LENGTH_SHORT).show();
		
		super.onError(objectId);
	}

	public ShowDialogOnDataUpdatedListener setErrorMessage(String mErrorMessage) {
		this.mErrorMessage = mErrorMessage;
		return this;
	}

	public ShowDialogOnDataUpdatedListener setRunningMesssage(
			String mRunningMesssage) {
		this.mRunningMesssage = mRunningMesssage;
		return this;
	}

	public ShowDialogOnDataUpdatedListener setSuccesMessage(
			String mSuccesMessage) {
		this.mSuccesMessage = mSuccesMessage;
		return this;
	}

	public ShowDialogOnDataUpdatedListener setDialogWindowText(
			String mDialogWindowText) {
		this.mDialogWindowText = mDialogWindowText;
		return this;
	}

}
